import axios from 'axios'
import {
	Message
} from 'element-ui';
import router from '@/router';
import envConfig from './env'


const service = axios.create({
	baseURL: envConfig.prodEnv.baseURL,
	timeout: 5000
})
service.interceptors.request.use(config => {
	if (config.url != '/login') {
		const token = sessionStorage.getItem('token')
		token && (config.headers['Authorization'] = token)
	}
	return config
}, error => { })

service.interceptors.response.use(res => {
	const {
		meta: {
			msg,
			status: code
		}
	} = res.data;
	const successsuccessStatusArr = [200, 201, 204]
	if (successsuccessStatusArr.includes(code)) {
		const {
			data: result
		} = res.data
		if (res.config.url === '/login') {
			sessionStorage.setItem('token', result.token)
			router.push('/home')
		}
		Message({
			message: msg,
			type: 'success'
		})

		return result

	}
	Message({
		message: msg,
		type: 'error'
	})

	if (msg === '无效token') {
		router.push('/login')
	}
	return msg
}, error => { 

	console.log(error)
})
export default service;
